<template>
  <div class="app-container flex h-screen overflow-hidden">
    <!-- 左侧面板 -->
    <div class="components-panel w-64 bg-gray-50 border-r border-gray-200 flex flex-col">
      <!-- 切换选项卡 -->
      <div class="flex border-b border-gray-200">
        <button class="flex-1 py-3 text-center text-sm font-medium"
          :class="{ 'border-b-2 border-primary text-primary': showPageManager, 'text-gray-500 hover:text-gray-700': !showPageManager }"
          @click="showPageManager = true">
          <i class="fa fa-file-o mr-1"></i> 页面管理
        </button>
        <button class="flex-1 py-3 text-center text-sm font-medium"
          :class="{ 'border-b-2 border-primary text-primary': !showPageManager, 'text-gray-500 hover:text-gray-700': showPageManager }"
          @click="showPageManager = false">
          <i class="fa fa-th mr-1"></i> 组件库
        </button>
      </div>

      <!-- 条件显示PageManager或组件库 -->
      <div v-if="showPageManager" class="flex-1 overflow-y-auto">
        <PageComponent :pages="pages" :current-page-id="currentPageId" @create-page="showPageModal = true"
          @switch-page="switchToPage" @edit-properties="openPagePropertiesModal" @rename-page="openRenameModal"
          @delete-page="confirmDeletePage" />
      </div>

      <div v-else class="flex flex-col h-full">
        <div class="p-4 border-b border-gray-200">
          <h2 class="font-semibold text-lg">组件库</h2>
          <p class="text-sm text-gray-500 mt-1">拖拽组件到画布中使用</p>
        </div>

        <div class="flex-1 overflow-y-auto">
          <!-- 标准组件库 -->
          <div class="p-3">
            <div v-for="(category, categoryName) in categorizedComponents" :key="categoryName">
              <h3 class="text-sm font-medium text-gray-500 mb-2">{{ categoryName }}</h3>
              <div class="grid grid-cols-2 gap-2 mb-4">
                <div v-for="component in category" :key="component.componentKey"
                  class="component-item bg-white p-3 rounded-md border border-gray-200 cursor-move hover:border-primary transition-colors flex flex-col items-center justify-center"
                  draggable="true" @dragstart="handleDragStart(component)">
                  <i :class="['fa', component.icon || 'fa-cube', 'text-primary text-xl mb-1']"></i>
                  <span class="text-xs text-center">{{ component.displayName }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 中间画布区域 -->
    <div class="canvas-container flex-1 flex flex-col overflow-hidden">
      <div class="canvas-toolbar p-2 border-b border-gray-200 flex justify-between items-center">
        <div class="flex items-center gap-2">
          <button class="p-2 hover:bg-gray-100 rounded" @click="handleUndo" :disabled="!canUndo">
            <i class="fa fa-undo text-gray-600"></i>
          </button>
          <button class="p-2 hover:bg-gray-100 rounded" @click="handleRedo" :disabled="!canRedo">
            <i class="fa fa-repeat text-gray-600"></i>
          </button>
          <div class="h-4 w-px bg-gray-300 mx-1"></div>
          <button class="p-2 hover:bg-gray-100 rounded" @click="handleSave">
            <i class="fa fa-save text-gray-600"></i>
          </button>
          <button class="p-2 hover:bg-gray-100 rounded" @click="handlePreview">
            <i class="fa fa-eye text-gray-600"></i>
          </button>
        </div>

        <div>
          <span class="text-sm text-gray-500">
            已选择: {{ selectedComponent ? selectedComponent.config.displayName : '无' }}
          </span>
        </div>
      </div>

      <div class="canvas-area flex-1 overflow-auto p-8 bg-gray-100" @dragover.prevent @drop.prevent="handleDrop">
        <div class="canvas-drop-zone bg-white min-h-[600px] max-w-6xl mx-auto shadow-sm">
          <!-- 画布组件 -->
          <component-renderer :components="canvasComponents" :is-editable="true"
            @update:components="updateCanvasComponents" @component-delete="handleComponentDelete"
            @components-reordered="handleComponentsReordered" @request-component-settings="handleComponentSettings"
            @component-added="handleComponentAdded">
          </component-renderer>

          <!-- 空画布提示 -->
          <div v-if="canvasComponents.length === 0" class="empty-canvas text-center py-20">
            <i class="fa fa-arrow-circle-left text-4xl text-gray-300 mb-4"></i>
            <p class="text-gray-400">从左侧组件库选择组件到此处开始构建页面</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧属性面板 -->
    <div class="properties-panel w-80 bg-white border-l border-gray-200 flex flex-col" v-if="showPropertiesPanel">
      <div class="p-4 border-b border-gray-200 flex justify-between items-center">
        <h2 class="font-semibold text-lg">属性设置</h2>
        <button class="text-gray-400 hover:text-gray-600" @click="handleCloseProperties">
          <i class="fa fa-times"></i>
        </button>
      </div>

      <div class="flex-1 overflow-y-auto p-1">
        <template v-if="fullySelectedComponent">
          <dynamic-property-editor :component-config="fullySelectedComponent.config"
            :component-props="fullySelectedComponent.props" :event-bindings="fullySelectedComponent.eventBindings"
            @update:componentProps="handlePropsUpdate"
            @update:eventBindings="handleEventBindingsUpdate"></dynamic-property-editor>
        </template>
        <template v-else>
          <div class="p-6 text-center text-gray-500">
            <i class="fa fa-hand-pointer-o text-2xl mb-2"></i>
            <p>请在画布中选择一个组件进行编辑</p>
          </div>
        </template>
      </div>
    </div>

    <!-- 预览模态框 -->
    <div v-if="isPreviewing" class="preview-modal fixed inset-0 bg-black/70 z-50 flex items-center justify-center p-4">
      <div class="preview-content bg-white w-full max-w-6xl max-h-[90vh] flex flex-col">
        <div class="preview-header p-4 border-b flex justify-between items-center">
          <h3 class="font-semibold">页面预览</h3>
          <button class="p-2 hover:bg-gray-100 rounded" @click="isPreviewing = false">
            <i class="fa fa-times"></i>
          </button>
        </div>
        <div class="preview-body p-8 overflow-auto">
          <component-renderer :components="canvasComponents" :is-editable="false"></component-renderer>
        </div>
      </div>
    </div>
  </div>

  <!-- 创建页面模态框 -->
  <CreatePageModal :visible="showPageModal" @close="showPageModal = false" @create="createNewPage" />

  <!-- 重命名页面模态框 -->
  <div v-if="showRenameModal" class="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50">
    <div class="bg-white rounded-lg p-6 w-full max-w-md">
      <h3 class="font-semibold text-lg mb-4">重命名页面</h3>
      <div class="mb-4">
        <label class="block text-sm font-medium text-gray-700 mb-1">页面名称</label>
        <input type="text" v-model="renamePageName"
          class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary"
          placeholder="请输入页面名称" @keyup.enter="renameCurrentPage">
      </div>
      <div class="flex justify-end gap-2">
        <button class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50"
          @click="showRenameModal = false">取消</button>
        <button class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary-dark"
          @click="renameCurrentPage">确认</button>
      </div>
    </div>
  </div>

  <!-- 删除页面确认模态框 -->
  <div v-if="showDeleteConfirm" class="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50">
    <div class="bg-white rounded-lg p-6 w-full max-w-md">
      <h3 class="font-semibold text-lg mb-4">删除页面</h3>
      <p class="text-gray-600 mb-6">确定要删除这个页面吗？删除后无法恢复。</p>
      <div class="flex justify-end gap-2">
        <button class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50"
          @click="showDeleteConfirm = false">取消</button>
        <button class="px-4 py-2 bg-red-500 text-white rounded-md hover:bg-red-600"
          @click="deleteCurrentPage">删除</button>
      </div>
    </div>
  </div>

  <!-- 页面属性编辑模态框 -->
  <PagePropertiesModal :visible="showPagePropertiesModal" :page="editingPageData"
    @close="showPagePropertiesModal = false" @save="savePageProperties" />
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue';
import ComponentRenderer from '../components/pages/ComponentRenderer.vue';
import DynamicPropertyEditor from '../components/pages/DynamicPropertyEditor.vue';
import PageManager from '../services/PageManager.js';
import PageComponent from '../components/pages/PageComponent.vue';
import CreatePageModal from '../components/pages/CreatePageModal.vue';
import PagePropertiesModal from '../components/pages/PagePropertiesModal.vue';


// 状态管理
const canvasComponents = ref([]);
const selectedIndex = ref(-1);
const showPropertiesPanel = ref(true);
const isPreviewing = ref(false);
const draggedComponent = ref(null);

const showPageManager = ref(true); // 控制显示PageManager还是组件库

// 页面管理状态
const pages = ref(PageManager.getAllPages());
const currentPageId = ref(PageManager.getCurrentPage()?.id);
const showPageModal = ref(false);
const showRenameModal = ref(false);
const renamePageId = ref('');
const renamePageName = ref('');
const showDeleteConfirm = ref(false);
const deletePageId = ref('');

// 历史记录管理
const history = ref([]);
const historyIndex = ref(-1);
const MAX_HISTORY = 50;

// 获取注册的组件库
const componentLibrary = computed(() => {
  return window.lowcodeComponentLibrary || [];
});

// 按分类组织组件
const categorizedComponents = computed(() => {
  const categories = {};

  componentLibrary.value.forEach(component => {
    const category = component.category || '未分类';
    if (!categories[category]) {
      categories[category] = [];
    }
    categories[category].push(component);
  });

  return categories;
});

// 当前选中的组件
const selectedComponent = computed(() => {
  if (selectedIndex.value >= 0 && selectedIndex.value < canvasComponents.value.length) {
    return canvasComponents.value[selectedIndex.value];
  }
  return null;
});

// 历史记录操作能力
const canUndo = computed(() => historyIndex.value > 0);
const canRedo = computed(() => historyIndex.value < history.value.length - 1);

// 初始化组件库
onMounted(() => {
  // 如果组件库不存在，初始化一个默认组件库
  if (!window.lowcodeComponentLibrary) {
    window.lowcodeComponentLibrary = [];
  }
  console.log('组件库数据:', window.lowcodeComponentLibrary);

  // 尝试加载保存的数据
  loadFromStorage();
});

// 刷新页面列表
const refreshPages = () => {
  pages.value = PageManager.getAllPages();
  currentPageId.value = PageManager.getCurrentPage()?.id;
};

// 创建新页面
const createNewPage = (newPageName) => {
  if (newPageName) {
    console.log(newPageName);
    PageManager.createPage(newPageName);
    showPageModal.value = false;
    refreshPages();
    loadFromStorage();
  } else {
    alert('请输入页面名称');
  }
};

// 切换页面
const switchToPage = (pageId) => {
  if (pageId !== currentPageId.value) {
    // 保存当前页面的组件
    PageManager.saveCurrentPageComponents(canvasComponents.value);

    // 切换页面
    PageManager.switchPage(pageId);
    refreshPages();

    // 加载新页面的组件
    loadFromStorage();

    // 重置选择状态
    selectedIndex.value = -1;
  }
};

// 显示重命名模态框
const openRenameModal = (page) => {
  renamePageId.value = page.id;
  renamePageName.value = page.name;
  showRenameModal.value = true;
};

// 重命名页面
const renameCurrentPage = () => {
  if (renamePageName.value.trim()) {
    PageManager.renamePage(renamePageId.value, renamePageName.value.trim());
    showRenameModal.value = false;
    refreshPages();
  } else {
    alert('请输入页面名称');
  }
};

// 确认删除页面
const confirmDeletePage = (pageId) => {
  deletePageId.value = pageId;
  showDeleteConfirm.value = true;
};

// 删除页面
const deleteCurrentPage = () => {
  const oldPageId = deletePageId.value;
  showDeleteConfirm.value = false;

  if (PageManager.deletePage(oldPageId)) {
    refreshPages();
    loadFromStorage();
    selectedIndex.value = -1;
  }
};

// 在 setup 函数中添加 restoreFromHistory 方法
const restoreFromHistory = (historyData) => {
  if (!Array.isArray(historyData)) return;

  // 重新构建组件数据结构，并重新关联组件构造函数
  const restoredComponents = historyData.map(component => {
    // 根据 componentKey 查找原始组件配置
    const originalComponentConfig = componentLibrary.value.find(
      comp => comp.componentKey === component.config.componentKey
    );

    return {
      id: component.id || `comp-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      config: {
        ...component.config,
        // 重新关联组件构造函数
        component: originalComponentConfig ? originalComponentConfig.component : null
      },
      props: component.props || {},
      eventBindings: component.eventBindings || {}
    };
  });

  canvasComponents.value = restoredComponents;
};

// 修改 handleUndo
const handleUndo = () => {
  if (canUndo.value) {
    historyIndex.value--;
    restoreFromHistory(history.value[historyIndex.value]);
  }
};

// 修改 handleRedo
const handleRedo = () => {
  if (canRedo.value) {
    historyIndex.value++;
    restoreFromHistory(history.value[historyIndex.value]);
  }
};

// 修改 saveHistory
const saveHistory = () => {
  // 移除当前位置后的历史
  if (historyIndex.value < history.value.length - 1) {
    history.value = history.value.slice(0, historyIndex.value + 1);
  }

  // 克隆当前状态，确保数据结构完整（不包含无法序列化的函数）
  const stateClone = canvasComponents.value.map(component => ({
    id: component.id,
    config: {
      componentKey: component.config.componentKey,
      displayName: component.config.displayName,
      description: component.config.description,
      icon: component.config.icon,
      category: component.config.category,
      version: component.config.version,
      configSchema: component.config.configSchema,
      events: component.config.events,
      actions: component.config.actions,
      defaultProps: component.config.defaultProps
      // 不包含 component 构造函数
    },
    props: { ...component.props },
    eventBindings: { ...component.eventBindings }
  }));

  history.value.push(stateClone);

  // 限制历史记录数量
  if (history.value.length > MAX_HISTORY) {
    history.value.shift();
  }

  historyIndex.value = history.value.length - 1;

  // 将数据持久化到本地存储
  PageManager.saveCurrentPageComponents(canvasComponents.value);
};

// 拖拽开始
const handleDragStart = (component) => {
  draggedComponent.value = component;
};
// 拖放处理
const handleDrop = () => {
  if (draggedComponent.value) {
    // 创建组件实例，确保包含id和isSelected属性
    const newComponent = {
      id: `comp-${Date.now()}`, // 生成唯一ID
      config: draggedComponent.value,
      props: { ...draggedComponent.value.defaultProps },
      eventBindings: {},
      children: draggedComponent.value.isContainer ? [] : undefined
    };
    canvasComponents.value.push(newComponent);
    selectedIndex.value = canvasComponents.value.length - 1;
    saveHistory();
  }
};
const handleComponentAdded = (index) => {
  const updatedComponent = [...canvasComponents.value];
  let parentComponent = updatedComponent[index];
  if (draggedComponent.value) {
    // 创建组件实例，确保包含id和isSelected属性
    const newComponent = {
      id: `comp-${Date.now()}`, // 生成唯一ID
      config: draggedComponent.value,
      props: { ...draggedComponent.value.defaultProps },
      eventBindings: {},
      children: draggedComponent.value.isContainer ? [] : undefined
    };
    if (parentComponent && parentComponent.children) {
      parentComponent.children.push(newComponent);
    }
    canvasComponents.value[index] = parentComponent;
    saveHistory();
    draggedComponent.value = null;
  }


}

// 组件删除
const handleComponentDelete = (index) => {
  canvasComponents.value.splice(index, 1);
  if (selectedIndex.value === index) {
    selectedIndex.value = -1;
  } else if (selectedIndex.value > index) {
    selectedIndex.value--;
  }
  saveHistory();
};

// 更新组件列表
const updateCanvasComponents = (newComponents) => {
  canvasComponents.value = newComponents;
  saveHistory();
};

// 属性更新
const handlePropsUpdate = (newProps) => {
  if (selectedComponent.value) {
    if (nestedComponentPath.value) {
      // 处理嵌套组件的属性更新
      console.log('更新嵌套组件属性:', nestedComponentPath.value, newProps);

      // 更新嵌套组件数据
      nestedComponentData.value.props = { ...newProps };

      // 通知父组件更新
      emit('child-event', {
        type: 'nested-component-update',
        data: {
          path: nestedComponentPath.value,
          props: newProps
        }
      });
    } else {
      // 创建新对象触发响应式更新
      canvasComponents.value = canvasComponents.value.map((comp, i) => {
        if (i === selectedIndex.value) {
          return { ...comp, props: { ...newProps } };
        }
        return comp;
      });
    }
    saveHistory();
  }
};

// 事件绑定更新
const handleEventBindingsUpdate = (newBindings) => {
  if (selectedComponent.value) {
    // 创建新对象触发响应式更新
    canvasComponents.value = canvasComponents.value.map((comp, i) => {
      if (i === selectedIndex.value) {
        return { ...comp, eventBindings: { ...newBindings } };
      }
      return comp;
    });
    saveHistory();
  }
};

// 处理组件重排序
const handleComponentsReordered = ({ oldIndex, newIndex, components }) => {
  console.log(`组件从 ${oldIndex} 移动到 ${newIndex}`);
  canvasComponents.value = [...components];

  // 如果选中的组件被移动，更新选中索引
  if (selectedIndex.value === oldIndex) {
    selectedIndex.value = newIndex;
  } else if (selectedIndex.value > oldIndex && selectedIndex.value <= newIndex) {
    selectedIndex.value--;
  } else if (selectedIndex.value < oldIndex && selectedIndex.value >= newIndex) {
    selectedIndex.value++;
  }

  saveHistory();
};

// 嵌套组件路径状态
const nestedComponentPath = ref(null);
const nestedComponentData = ref(null);

// 当前选中的完整组件（包括嵌套组件）
const fullySelectedComponent = computed(() => {
  if (!nestedComponentPath.value || !nestedComponentData.value) {
    return selectedComponent.value;
  }

  // 返回嵌套组件数据
  return nestedComponentData.value;
});

// 处理组件设置请求
const handleComponentSettings = (settingsData) => {
  if (typeof settingsData === 'number') {
    // 处理顶层组件的设置请求
    selectedIndex.value = settingsData;
    nestedComponentPath.value = null;
    nestedComponentData.value = null;
  } else if (typeof settingsData === 'object' && settingsData.index !== undefined) {
    // 处理嵌套组件的设置请求
    console.log('处理嵌套组件设置请求:', settingsData);
    selectedIndex.value = settingsData.index;

    // 保存嵌套组件的路径信息和组件数据
    nestedComponentPath.value = settingsData.path;
    nestedComponentData.value = settingsData.childComponent;

    console.log('嵌套组件路径:', settingsData.path);
    console.log('嵌套组件:', settingsData.childComponent);
  }
  showPropertiesPanel.value = true;
};

// 关闭属性面板
const handleCloseProperties = () => {
  showPropertiesPanel.value = false;
};


// 保存操作
const handleSave = () => {
  PageManager.saveCurrentPageComponents(canvasComponents.value);
  alert('页面已保存');
};

// 预览操作
const handlePreview = () => {
  // 取消所有组件的选择状态
  selectedIndex.value = -1;
  isPreviewing.value = true;
};

// 从PageManager加载组件数据
const loadFromStorage = () => {
  const components = PageManager.loadCurrentPageComponents();
  if (components && components.length > 0) {
    // 重新构建组件数据结构，并重新关联组件构造函数
    const restoredComponents = components.map(component => {
      // 根据 componentKey 查找原始组件配置
      const originalComponentConfig = componentLibrary.value.find(
        comp => comp.componentKey === component.config.componentKey
      );

      return {
        id: component.id || `comp-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
        config: {
          ...component.config,
          // 重新关联组件构造函数
          component: originalComponentConfig ? originalComponentConfig.component : null
        },
        props: component.props || {},
        eventBindings: component.eventBindings || {}
      };
    });

    canvasComponents.value = restoredComponents;
  } else {
    // 如果没有数据，初始化为空数组
    canvasComponents.value = [];
  }
};

// 页面属性编辑相关状态
const showPagePropertiesModal = ref(false);
const editingPageId = ref('');
const editingPageData = ref({
  id: '',
  name: '',
  title: '',
  route: '',
  seo: {
    title: '',
    description: '',
    keywords: []
  }
});

// 打开页面属性编辑模态框
const openPagePropertiesModal = (page) => {
  editingPageId.value = page.id;
  editingPageData.value = {
    id: page.id,
    name: page.name,
    title: page.title || '',
    route: page.route || '',
    seo: {
      title: page.seo?.title || '',
      description: page.seo?.description || '',
      keywords: page.seo?.keywords || []
    }
  };
  showPagePropertiesModal.value = true;
};

// 保存页面属性
const savePageProperties = (pageData) => {
  // 验证路由格式
  if (pageData.route && !pageData.route.startsWith('/')) {
    alert('路由必须以斜杠(/)开头');
    return;
  }

  // 验证路由是否已存在（排除当前页面）
  if (pageData.route &&
    PageManager.isRouteExists(pageData.route, pageData.id)) {
    alert('该路由已被其他页面使用');
    return;
  }

  // 更新页面SEO设置
  PageManager.updatePageSEO(pageData.id, pageData.seo);

  // 更新页面标题
  if (pageData.title) {
    PageManager.updatePageTitle(pageData.id, pageData.title);
  }

  // 更新页面路由
  if (pageData.route) {
    PageManager.updatePageRoute(pageData.id, pageData.route);
  }

  showPagePropertiesModal.value = false;
  refreshPages();

};
</script>

<style scoped>
.app-container {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

.component-item {
  transition: all 0.2s ease;
}

.component-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.canvas-component-wrapper {
  transition: all 0.2s ease;
}

.component-highlight {
  outline: 2px solid #165DFF;
}

.empty-canvas {
  color: #9ca3af;
}

.preview-modal {
  animation: fadeIn 0.3s ease;
}

.preview-content {
  animation: slideUp 0.3s ease;
  border-radius: 0.5rem;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

@keyframes slideUp {
  from {
    transform: translateY(20px);
    opacity: 0;
  }

  to {
    transform: translateY(0);
    opacity: 1;
  }
}
</style>